package connections;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public class FilePoster extends Thread{

	String extraInfo;

	String url;

	byte[] outputArray;
	
	StringBuffer feedback;

	public FilePoster( byte[] _outputArray, String _url, String _extraInfo) {

		outputArray = _outputArray;
		if (outputArray != null) {
			url = _url;
			extraInfo = encode(_extraInfo, "UTF-8");
			start(); // calls the run method in a way that doesn't stall other processes
		} else {
			put("nothing to send");
		}
	}
	public FilePoster( byte[] _outputArray, String _url, String _extraInfo, StringBuffer _feedback) {
		feedback = _feedback;
		outputArray = _outputArray;
		if (outputArray != null) {
			url = _url;
			extraInfo = encode(_extraInfo, "UTF-8");
			start(); // calls the run method in a way that doesn't stall other processes
		} else {
			put("nothing to send");
		}
	}

	public void put(String _s) {
		System.out.println(_s);
		if (feedback != null){
			feedback.delete(0, feedback.length());
			feedback.append(_s);
		}
	}
	public FilePoster( String _url) {
		url = _url;
	}
	public void addFeedback(StringBuffer _feedback){
		feedback = _feedback;
	}
	public void send(byte[] _outputArray,String _extraInfo) {

		outputArray = _outputArray;
		if (outputArray != null) {
			//extraInfo = _extraInfo;
			extraInfo = encode(_extraInfo, "UTF-8");
			start(); // calls the run method in a way that doesn't stall other processes
		} else {
			System.out.println("nothing to send");
		}
	}
	public void run() {

		InputStream is = null;
		String response = "Server Response:";

		try {
			
			//"http://itp.nyu.edu/~dbo2/up.php?loc=25&temp=99"
			HttpConnection c = (HttpConnection) Connector.open(url);

			// /MAKE AND SEND A HEADER
			
			c.setRequestMethod(HttpConnection.POST);
		
			c.setRequestProperty("Content-Type", "multipart/form-data, boundary=AaB03x");
			DataOutputStream dataOut = new DataOutputStream(c.openOutputStream());
			//String boundary = \r\n";
			dataOut.write(("--AaB03x\r\n").getBytes());
			dataOut.write(("Content-Disposition: form-data; name=\"data_file\"; filename=\"" + extraInfo + "\"\r\n").getBytes());
			dataOut.write(("Content-Type: " + "image/png" + " \r\n").getBytes());
	
			dataOut.write("\r\n".getBytes());

			// /SEND THE BODY
			dataOut.write(outputArray, 0, outputArray.length);

			// SEND THE END
			dataOut.write("\r\n--AaB03x--\r\n".getBytes());
			dataOut.flush();
			put("waiting for server");

			// receive response and display in a text box.
			is = c.openDataInputStream();
			int ch;
			while ((ch = is.read()) != -1) {
				response = response + (char) ch;
			}

			
			dataOut.close();
			is.close();
			c.close();
		} catch (IOException e) {
			put("Problem with post " + e);
		}

		put(" size:" + outputArray.length + " " + response);

	}

	/*
	 * This is the php that can receive the above post. You can paste this into a file names "something.php" in somewhere in your public_html directory You will need to also put a world writable directory named "up" in the same directory that you put that file. The url that you send to this class will have to point to the php file that you put on your machine
	 * 
	 *  <? //This is a function used later on for testing extenstions //skip it for now function endsWith( $str, $sub ) { return ( substr( $str, strlen( $str ) - strlen( $sub ) ) === $sub ); } //get ready unset($filename);
	 * 
	 * //get the files in from the post if(!isset($_FILES) && isset($HTTP_POST_FILES)) $_FILES = $HTTP_POST_FILES; //if no file was sent if(!isset($_FILES['data_file'])) $error["data_file"] = "An data file was not found.";
	 * 
	 * $filename = urldecode($_FILES['data_file']['name'] ); //this will contain the extra information that you sent over //if they don't have a path name use the default of an "up" //folder in the current directory. This requires you to have a //world writable "up" directory in the same directory as up.php $pos = strpos($filename,"/home/"); if ($pos === false) { $filename = "./up/" . $filename; } //if they did not send over any filename if(empty($filename)) $error["filename"] = "The name of the file was not found.";
	 * 
	 * //if there were no previous problems if(empty($error)) { //security measure, only good file extensions get in if (endsWith($filename, ".png") || endsWith($filename,".jpg") || endsWith($filename,".log")){ //this is it, move and name the file within the server $result = @move_uploaded_file($_FILES['data_file']['tmp_name'], $filename ); if(empty($result)) $error["result"] = "There was an error moving the uploaded file."; }else{ $error["extension"] = "Bad File Extension."; }
	 *  }
	 * 
	 * 
	 * if(is_array($error)) { //send back the litany of errors while(list($key, $val) = each($error)) { echo $val; echo "<br>\n"; } }else{ //send back a sunny message $size = filesize($tmp ); echo "OK: $size bytes FILENAME: $filename "; }
	 *  ?>
	 * 
	 * 
	 * 
	 */

	/*
	 * this function was taken from the Java forums, at http://forum.java.sun.com/thread.jspa?forumID=76&messageID=624066&threadID=178903 and modified to behave like the original one. @param s string to encode @param enc normally, this would be "UTF8", but here it is ignored. @throws IOException on IO error @return an encoded version of the string <CODE>s</CODE>
	 */
	public String encode(String s, String enc) {
		StringBuffer ret = new StringBuffer(); // return value

		try {
			ByteArrayOutputStream bOut = new ByteArrayOutputStream();
			DataOutputStream dOut = new DataOutputStream(bOut);
			dOut.writeUTF(s);
			ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
			bIn.read();
			bIn.read();
			int c = bIn.read();
			while (c >= 0) {
				if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '*' || c == '_')
					ret.append((char) c);
				else if (c == ' ')
					ret.append('+');
				else {
					if (c < 128) {
						appendHex(c, ret);
					} else if (c < 224) {
						appendHex(c, ret);
						appendHex(bIn.read(), ret);
					} else if (c < 240) {
						appendHex(c, ret);
						appendHex(bIn.read(), ret);
						appendHex(bIn.read(), ret);
					}

				}
				c = bIn.read();

			}
		} catch (IOException e) {
			System.out.println("hey");
		}
		return ret.toString();
	}

	private void appendHex(int arg0, StringBuffer buff) {
		buff.append('%');
		if (arg0 < 16)
			buff.append('0');
		buff.append(Integer.toHexString(arg0));
	}

}
